bits 16

findbootbin:

    ;bp+2   =   ret address
    ;bp     =   last stack bp
    ;bp-2   =   SectorNumOfRootDirStart => use for loop 
    ;bp-4   =   BPB_RootDirSectors      => use for loop
    ;bp-6   =   BootBin Cluster Num   
    ;bp-8   =   BootBin Load Addr
    ;bp-10   =  Fat Odd Or Even
    
    push bp
    mov bp,sp
    sub sp,10
    mov word [bp-2],SectorNumOfRootDirStart
    mov word [bp-4],BPB_RootDirSectors
    mov word [bp-6],0
    mov word [bp-8],0
    mov word [bp-10],0

.label_search_in_root_dir_begin:

    mov ax,[bp-4]  
    cmp ax,0
    je .label_no_bootbin

    push 0x8000
    push word [bp-2]
    call readdisk
    add sp,4

    mov si,.bootbin_name
    mov di,0x8000
    cld
    mov dx,RootEntCntPerSec

.label_search_for_bootbin:

    cmp dx,0
    je .label_nextsector
    mov cx,7

.label_cmp_bootbin_name:

    cmp  cx,0
    je .label_filename_found
    lodsb
    cmp  al,[di]
    jz .label_next_char
    jmp .label_different
    

.label_next_char:
    dec cx
    inc di
    jmp .label_cmp_bootbin_name

.label_different:

    dec dx
    and di,0xffe0
    add di,0x20
    mov si,.bootbin_name
    jmp .label_search_for_bootbin

.label_nextsector:
    dec word [bp-4]
    inc word [bp-2]
    jmp .label_search_in_root_dir_begin
    
; .label_ret:

;     mov sp,bp
;     pop bp
;     ret

.label_no_bootbin:
    ; push 1
    ; push 6
    ; push .bootbin_not_found
    ; call logprint
    ; add sp,6
    jmp $

.label_filename_found:
    push 1
    push 7
    push .bootbin_name
    call logprint
    add sp,6

    and di,0xffe0
    mov ax,[di+26]
    mov [bp-6],ax

.label_load_bootbin:


    ;FirstSectorofCluster = ((N - 2) * BPB_SecPerClus) + FirstDataSector;
    mov word ax,[bp-6]
    sub ax,2
    add ax,SectorNumOfDataStart 
    
    push word [bp-8]
    push ax
    mov  ax,0x1000
    mov  es,ax
    call readdisk
    mov  ax,0
    mov  es,ax
    add  sp,4
    

    add word [bp-8],512

.label_check_fattable:

;     ; mul乘法，被乘数、乘数、乘积的表格如下
;     ; 被乘数	乘数	乘积
;     ; AL	reg/mem8	AX
;     ; AX	reg/mem16	DX:AX
;     ; EAX	reg/mem32	EDX:EAX
    mov word [bp-10],0
    xor dx,dx
    mov ax,[bp-6]
    mov bx,3
    mul bx   ;this code assume ax = ax*bx not dx:ax = ax*bx 

    xor dx,dx
    mov bx,2
    div bx
    cmp dx,0
    jz .label_even
    mov word [bp-10],1

.label_even:

    xor dx,dx
    mov bx,BPB_BytesPerSec
    div bx

    push dx
    push 0x8000
    add  ax,SectorNumOfFATlStart
    push ax
    call readdisk
    add  sp ,4
    pop  dx

    add dx,0x8000
    mov bx,dx
    mov ax,[bx]
    cmp byte [bp-10],1
    jnz .label_even_2
    shr ax,4

.label_even_2:
    and ax,0x0fff
    mov word [bp-6],ax

    cmp ax,0x0fff
    jz $
    jmp .label_load_bootbin

; .bootbin_not_found
;     db"NO"
.bootbin_name:
    db "BOOTBIN"

; .bootbin_found:
    ; db "okboot"